<template>
  <div class="app-container" v-loading="dialogVisible">
    <!-- <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" @close="closeTag"> -->
      <div v-if="$store.state.mobile.userAgent==='mobile' && !dialogVisible">
      <back-page path="/iphonePath/首页"></back-page>
<mobile-parser :form-conf="formConfData" :tableName="tableName" @submit="submit" status="add" 
    :originData="originData" :key="time" ref="parser" @reset="reset" @cancel="closeTag('mobile')"></mobile-parser>
      </div>
    <div style="display:flex;justifyContent:center;" v-if="$store.state.mobile.userAgent==='pc'">
      <parser :form-conf="formConfData" :tableName="tableName" @submit="submit" status="add" :originData="originData" :key="time" ref="parser"
        v-if="!dialogVisible && $store.state.mobile.userAgent==='pc'" style="width:80%;" @reset="reset" @cancel="closeTag"/>
    </div>
    <!-- </el-dialog> -->
  </div>
</template>
<script>
  import Parser from './parser'
  import mobileParser from '../../../mobileCustom/components/parser'
  import {
    getFormInfo,
    insertData,
    updateData
  } from '@/api/custom/formDesigner'
  import { createProcessInstance } from "@/api/bpm/processInstance";
  import { getProcessIn, insertdatalist } from "@/api/custom/formPoster";
  const arrTypes = ['cascader', 'checkbox', 'time-range', 'date-range','tree-table']; //值为数组组件
  export default {
    name: 'formsubmit',
    components: {
      Parser,
      mobileParser
    },
    data() {
      return {
        dialogVisible: true,
        formConfData: {}, //表单配置
        tableName: '', //表名
        dialogTitle: '', //弹窗名
        fieldData: [], //表字段
        originData: {}, //表单原始数据
        time: '', //当前时间秒数
        formId: '', //表单id
        variables: {},
        tagIcons: [], //组件tagIcon
        tableFiledsMap: new Map() // 子表单字段使用
      }
    },
    mounted() {
      // if (this.$route.params.formName) {
      //   this.$route.meta.title = this.$route.params.formName
      //   this.dialogTitle = this.$route.params.formName
      // } else {
      //   this.dialogTitle = this.$route.name
      // }
      this.getFormDetail() //获取表单详情
    },
    methods: {
      //根据id获取表单详情，赋值渲染表单
      getFormDetail() {
        let path = this.$route.path.split('/')
        getFormInfo(path[path.length - 1]).then((res) => {
          if (res.code === 0) {
            this.formId = res.data.id
            this.tableName = res.data.tableName
            this.formConfData = JSON.parse(res.data.formJsonUser)
            this.formConfData.formName = res.data.formName
            this.getTagIcons(this.formConfData.fields)
            this.fieldData = JSON.parse(res.data.formJsonData).data
            if (res.data.childFormJsonData) {
                const tempList = JSON.parse(res.data.childFormJsonData)
                tempList.forEach(test => {
                    const jsonData = JSON.parse(test.formJsonData)
                    jsonData.forEach(jay => {
                        this.tableFiledsMap.set(test.tableName + '-' + jay.name, jay)
                    })
                })
            }
            this.time = new Date().getMilliseconds()
            this.dialogVisible = false
          }
        }).catch(e => console.log(e))
      },
      //数据格式化成对应数据库存储类型
      getFormatValue(data, tag, format) {
        if (arrTypes.includes(tag)) { //组件数据类型为数组
          return data.toString()
        }
        if (tag === 'upload') {
          return JSON.stringify(data)
        }
        if ((format === 'int' || format === 'double'|| format === 'decimal') && !Number.isNaN(data)) { //数据库存储类型为int或double，但组件数据类型为字符串
          if(tag === "number"){
            return data!==''?data:''
          }
          return data!==''?Number(data):''
        }
        if (format === 'varchar') {
          return data.toString()
        }
        return data
      },
      //获取各组件的tagIcon
      getTagIcons(data) {
        if (data.length === 0) return
        data.filter((item) => {
          return item.__config__.tag !== 'TitleLine' //过滤标题和分割线组件
        }).map((item) => {
          if (item.__config__.tag === 'el-card' || item.__config__.tag === 'el-tabs' || item.__config__.tag === 'Steps'|| item.__config__.tag === 'el-collapse') {
            //布局组件，遍历内部子组件
            let tem = item.__config__.children.map((c) => {
              this.getTagIcons(c.__config__.children)
            })
          } else { //一般组件
            this.tagIcons.push(item.__config__.tagIcon)
          }
        })
      },
      //提交数据
      submit(data, valueMap) {
        const tableValueList = []
        // 组装子表单数据批量插入
        if (valueMap.size > 0) {
            for (let [k, v] of valueMap) {
                v.forEach(params => {
                    const obj = {}
                    obj.data = []
                    delete params.id
                    delete params.showComp
                    const keyLst = Object.keys(params)
                    keyLst.forEach(insideKey => {
                        const tempObj = {}
                        tempObj.type = this.tableFiledsMap.get(k + '-' + insideKey).format
                        tempObj.name = insideKey
                        tempObj.value = params[insideKey]
                        obj.data.push(tempObj)
                    })
                    obj.tableName = k
                    tableValueList.push(obj)
                })
            }
        }
        let fields = []
        this.fieldData.map((item, index) => {
          if (data[item.name] !== undefined && data[item.name] !== null) {
            let value = this.getFormatValue(data[item.name], this.tagIcons[index], item.format) //格式化数据，转化成数据库存储类型
            fields.push({
              name: item.name,
              type: item.format,
              value: value
            })
          }
        })
      this.variables = data
        insertData({
          tableName: this.tableName,
          dataType: '1',
          data: fields
        }).then((res) => {
          if (res.code === 0) {
            const data = res.data
            tableValueList.forEach(item => {
                item.data.push({
                    name: 'parent_id',
                    type: 'bigint',
                    value: res.data
                })
            })
            insertdatalist(tableValueList)
            getProcessIn(this.formId).then((res) => {
                if(res.data){ //关联实例
                  createProcessInstance({
                    formId: this.formId,
                    formRecordId: data,
                    variables: this.variables
                  }).then(res => {})
                  this.$message.success('提交成功')
                  this.$refs.parser.resetForm()
                  // this.time = new Date().getMilliseconds()
                }else{
                  this.$message.success('提交成功')
                  this.$refs.parser.resetForm()
                  // this.time = new Date().getMilliseconds()
                }
            })
          }
        }).catch(e => console.log(e))
      },
      //重置表单，更新时间秒数
      reset() {
        this.time = new Date().getMilliseconds()
      },
      //关闭标签
      closeTag(type) {
        if(type==='mobile'){
         this.$router.push('/iphonePath/首页');
        }else{
          this.$store.dispatch('tagsView/delView', this.$route).then(({
          visitedViews
        }) => {
          this.toLastView(visitedViews, this.$route)
        })
        }
      },
      //跳转到上一页
      toLastView(visitedViews, view) {
        const latestView = visitedViews.slice(-1)[0]
        if (latestView) {
          this.$router.push(latestView.fullPath)
        } else {
          if (view.name === 'Dashboard') {
            this.$router.replace({
              path: '/redirect' + view.fullPath
            })
          } else {
            this.$router.push('/')
          }
        }
      },
    }
  }

</script>
